<template>
  <div class="case-list" v-if="new Date().getTime()">
    <div class="list-serach">
      <div>
        <a-select
          defaultValue="全部"
          dropdownMatchSelectWidth
          :options="classifyOptions"
          @change="getCaseByClassifyId"
          v-model="select"
        >
        </a-select>
        <a-input-search
          size="default"
          v-model="searchId"
          placeholder="请输入案例id"
          enter-button
          @search="searchById"
        />
      </div>
      <div>
        <a-button type="primary" @click="classifyModal = true"
          >分类管理</a-button
        >
        <a-button type="primary" @click="resetSearch">重置搜索条件</a-button>
      </div>
    </div>
    <a-modal centered title="分类管理" v-model="classifyModal" :footer="null">
      <div>
        <template v-for="tag in classifyList">
          <a-tag color="#2db7f5" :key="tag.id">
            <span @click="handleEdit(tag)"
              >ID: {{ tag.id }} {{ tag.name }}</span
            >
            <a-icon type="close" @click="handleClose(tag)" />
          </a-tag>
        </template>
        <a-input
          v-if="inputVisible"
          ref="input"
          type="text"
          placeholder="按回车保存"
          :style="{ width: '100px' }"
          :value="inputClassifyValue"
          @change="handleInputChange"
          @blur="inputVisible = false"
          @keyup.enter="addClassify"
        />
        <a-tag
          v-else
          style="background: #fff; borderstyle: dashed"
          @click="showInput"
        >
          <a-icon type="plus" /> 添加分类
        </a-tag>
      </div>
    </a-modal>
    <a-modal
      centered
      :title="classifyTitle"
      v-model="classifyConfirm"
      @ok="handleClassify"
      @cancel="classifyConfirm = false"
    >
      <p v-if="classifyTitle == '删除分类'">此操作不可逆！确认删除？</p>
      <a-input v-else v-model="currentClassify.name" type="text" />
    </a-modal>
    <a-table
      :row-selection="{
        selectedRowKeys: selectedRowKeys,
        onChange: onSelectChange,
      }"
      :columns="columns"
      :data-source="caseList"
      :pagination="false"
      :rowKey="(record) => record.id"
    >
      <span slot="pic" slot-scope="text, record">
        <img
          style="
            width: 100px;
            height: 100px;
            border-radius: 5%;
            box-shadow: 2px 2px 5px #333333;
          "
          :src="record.cover"
        />
      </span>
      <span slot="projectName">
        <span>{{ projectName }}</span>
      </span>
      <span slot="action" slot-scope="text, record">
        <a-button
          type="primary"
          style="margin-right: 8px"
          icon="eye"
          @click="showDetail(record.id)"
          >查看</a-button
        >
        <a-button
          type="danger"
          style="margin-right: 8px"
          icon="delete"
          @click="delSingle(record.id)"
          >删除</a-button
        >
      </span>
    </a-table>
    <div class="bottom">
      <div class="button-group">
        <a-button type="primary" icon="plus" class="add" @click="addCase">
          新增
        </a-button>
        <a-button type="danger" class="del-list-btn" @click="delAll"
          >删除选中</a-button
        >
      </div>
      <a-pagination
        class="pageTab"
        show-quick-jumper
        :current="current"
        :page-size-options="pageSizeOptions"
        :total="caseNum"
        :show-total="(total) => `共 ${caseNum} 条`"
        :page-size="limit"
        :default-current="1"
        show-size-changer
        @showSizeChange="onShowSizeChange"
        @change="pageChange"
      />
      <a-modal
        centered
        title="删除案例"
        v-model="delModalVisible"
        @ok="delOk"
        @cancel="delNo"
      >
        <p>此操作不可逆！确认删除？</p>
      </a-modal>
    </div>
  </div>
</template>

<script>
import {
  delCaseApi,
  getCaseListApi,
  getCaseByIdApi,
  getClassifyListApi,
  addClassifyApi,
  editClassifyApi,
  delClassifyApi,
  getCaseByClassifyIdApi,
} from '@/services/webApi/case';
import moment from 'moment';
export default {
  data() {
    return {
      columns: [
        {
          title: '案例id',
          dataIndex: 'id',
          key: 'caseId',
          align: 'center',
        },
        {
          title: '案例标题',
          dataIndex: 'name',
          key: 'name',
          align: 'center',
        },
        {
          title: '封面图片',
          dataIndex: 'cover',
          key: 'cover',
          scopedSlots: { customRender: 'pic' },
          align: 'center',
        },
        {
          title: '所属人物id',
          dataIndex: 'characterId',
          key: 'characterId',
          align: 'center',
        },
        {
          title: '项目名称',
          scopedSlots: { customRender: 'projectName' },
          key: 'projectName',
          align: 'center',
        },
        {
          title: '创建时间',
          dataIndex: 'createdAt',
          key: 'createdAt',
          align: 'center',
        },
        {
          title: '操作',
          key: 'action',
          scopedSlots: { customRender: 'action' },
          align: 'center',
        },
      ],
      classifyColumns: [
        {
          title: '分类名',
          dataIndex: 'name',
          key: 'name',
          align: 'center',
        },
        {
          title: '操作',
          key: 'action',
          scopedSlots: { customRender: 'action' },
          align: 'center',
        },
      ],
      searchId: '',
      caseNum: 0, //案例数量
      pageSizeOptions: ['5', '10', '15', '20', '25'], //每页案例数选择
      current: 1, //当前页面
      limit: 5, //每页多少条
      caseList: [],
      selectedRowKeys: [], //选择的列数
      delModalVisible: false,
      currentCaseId: 0,
      action: '', // 删除单条还是多条
      projectName: '',
      classifyOptions: [],
      classifyModal: false,
      classifyList: [],
      inputVisible: false,
      inputClassifyValue: '',
      classifyConfirm: false,
      currentClassify: '',
      classifyTitle: '',
      select: 0,
    };
  },
  async created() {
    this.getCaseList(this.limit, 0);
    this.getClassifyList();
  },
  methods: {
    handleClose(removedTag) {
      this.currentClassify = removedTag;
      this.classifyConfirm = true;
      this.classifyTitle = '删除分类';
    },
    handleEdit(tag) {
      this.classifyConfirm = true;
      this.classifyTitle = '编辑分类';
      this.currentClassify = tag;
    },
    handleClassify() {
      if (this.classifyTitle == '删除分类') {
        delClassifyApi({ id: this.currentClassify.id }).then((res) => {
          if (res.code == 200) {
            this.classifyConfirm = false;
            this.classifyList = this.classifyList.filter(
              (tag) => tag.id !== this.currentClassify.id
            );
            this.currentClassify = '';
            this.$message.success(`删除成功`);
          }
        });
      } else {
        editClassifyApi({
          name: this.currentClassify.name,
          id: this.currentClassify.id,
        }).then((res) => {
          if (res.code == 200) {
            this.classifyConfirm = false;
            this.currentClassify = '';
            this.$message.success(`修改成功`);
          }
        });
      }
    },
    showInput() {
      this.inputVisible = true;
      this.$nextTick(function() {
        this.$refs.input.focus();
      });
    },
    handleInputChange(e) {
      this.inputClassifyValue = e.target.value;
    },
    addClassify() {
      if (!this.inputClassifyValue) {
        this.$message.error('不能为空');
        return;
      }
      if (
        this.classifyList.find((ele) => ele.name == this.inputClassifyValue)
      ) {
        this.$message.error('分类名重复');
        return;
      }
      addClassifyApi({ name: this.inputClassifyValue }).then((res) => {
        if (res.code == 200) {
          this.inputClassifyValue = '';
          this.inputVisible = false;
          this.classifyList.push(res.data);
        }
      });
    },
    getClassifyList() {
      this.classifyOptions = [{ label: '全部', value: 0 }];
      getClassifyListApi().then((res) => {
        this.classifyList = res.data.rows;
        res.data.rows.forEach((ele) => {
          this.classifyOptions.push({ label: ele.name, value: ele.id });
        });
      });
    },
    // 下拉框选择
    getCaseByClassifyId(value) {
      if (value === 0) {
        this.getCaseList(this.limit, 0);
        return;
      }
      getCaseByClassifyIdApi({ id: value }).then((res) => {
        this.caseList = res.data.w_cases;
        this.caseList.forEach((ele) => {
          ele.createdAt = moment(ele.createdAt).format('YYYY-MM-DD  HH:mm:ss');
        });
      });
    },
    // 新增案例d
    addCase() {
      this.$router.push(`casedetail/0`);
    },
    // 分组选择
    handleClassifyChange(value) {},
    // 重置搜索
    async resetSearch() {
      this.searchId = '';
      this.$message.success(`重置搜索条件成功`, 1.5);
      this.getCaseList(this.limit, 0);
      this.caseList = [];
      this.current = 1;
      this.select = 0;
    },
    // 按id搜索
    searchById() {
      if (!this.searchId) {
        return;
      }
      this.getCaseById();
    },
    async getCaseById() {
      try {
        let res = await getCaseByIdApi({
          id: this.searchId - 0,
        });
        this.caseList = res.data ? [res.data] : [];
        if (this.caseList) {
          this.caseList[0].createdAt = moment(
            this.caseList[0].createdAt
          ).format('YYYY-MM-DD  HH:mm:ss');
        }
        this.caseNum = this.caseList.length;
      } catch (error) {
        this.searchId = '';
        this.$message.error(`请重新输入`, 1);
        setTimeout(() => {
          this.getCaseList(this.limit, 0);
          this.current = 1;
        }, 1000);
      }
    },
    // 获取案例列表
    async getCaseList(limit, offset) {
      let res = await getCaseListApi({
        limit,
        offset,
      });
      this.caseList = res.data.rows;
      this.caseList.forEach((ele) => {
        ele.createdAt = moment(ele.createdAt).format('YYYY-MM-DD  HH:mm:ss');
        ele.updatedAt = moment(ele.updatedAt).format('YYYY-MM-DD  HH:mm:ss');
      });
      this.caseNum = res.data.count;
      this.projectName = res.data.projectName;
    },
    // 跳转案例详情
    showDetail(id) {
      this.$router.push(`/web/case/caseDetail/${id}`);
    },
    // 删除单条modal框
    delSingle(id) {
      this.currentCaseId = id;
      this.delModalVisible = true;
      this.action = 'deleteSingle';
    },
    // 删除多条modal框
    delAll() {
      this.action = 'deleteAll';
      let flag = this.selectedRowKeys.length;
      if (flag == 0) {
        this.$message.error('未选中任何案例', 1);
      } else {
        this.delModalVisible = true;
      }
    },
    // 确认删除
    async delOk() {
      switch (this.action) {
        case 'deleteSingle': {
          let res = await this.delCase();
          res.code == 200 && this.$message.success(res.msg, 1);
          this.delModalVisible = false;
          break;
        }
        case 'deleteAll':
          this.delAllCase();
          break;
      }
      this.searchId = '';
      // 请求新数据
      this.getCaseList(this.limit, 0);
      this.current = 1;
    },
    //删除操作
    async delCase(id = this.currentCaseId) {
      this.currentCaseId = '';
      return await delCaseApi({
        id,
      });
    },
    // 删除多条的操作
    delAllCase() {
      let delArr = this.selectedRowKeys;
      try {
        delArr.map((ele) => {
          this.delCase(ele);
        });
      } catch (error) {
        this.$message.error('删除失败', 1);
      }
      this.$message.success(`成功删除${delArr.length}条案例`, 1);
      this.selectedRowKeys = [];
      this.delModalVisible = false;
    },
    // 取消删除
    delNo() {
      this.delModalVisible = false;
      this.$message.info('取消删除', 1);
    },
    // 多选
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
    },
    // 分页
    onShowSizeChange(current, pageSize) {
      this.limit = pageSize;
      this.pageChange(current);
    },
    pageChange(current) {
      this.current = current;
      let offset = (this.current - 1) * this.limit;
      this.getCaseList(this.limit, offset);
    },
  },
};
</script>

<style lang="scss" scoped>
.add {
  margin-bottom: 10px;
}
button {
  margin-right: 10px;
}
.list-serach {
  display: flex;
  justify-content: space-between;
  gap: 1rem;
  margin-bottom: 1rem;
  .ant-input-search {
    width: 200px;
  }
  .admin-search {
    .ant-select {
      min-width: 80px;
      .ant-select-selection {
        display: flex;
        flex-direction: column;
      }
    }
  }
  .ant-input-group {
    display: flex;
  }
}
.bottom {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 1rem;
  .pageTab {
    text-align: right;
  }
  .del-list-btn {
    text-align: center;
  }
}
.ant-tag {
  margin-bottom: 10px;
  height: 28px;
  line-height: 25px;
  font-size: 16px;
  cursor: pointer;
}
</style>
